﻿using Azure.Core;
using DataModels.Dto;
using DataModels.Dto.WorkOrder;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.WorkOrder;
using DataModels.Enums.WorkOrder;
using Dm;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Services.AuthCore;
using Services.House;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Utils;
using static DataModels.Enums.GeneralEnum;

namespace Services.OpenDoor
{
    public class Open3UnitService(SqlSugarClient db, UserService UserService, IConfiguration configuration) : BaseService(db)
    {
        protected readonly UserService _userService = UserService;


        private readonly string ip;
        private readonly string port;
        private readonly string address;
        private readonly string aesKey;

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResponseModel Open3UnitByName(string DoorName)
        {
            //权限在列表的时候控制
            //数据库根据名称查询 device_id(sn)
            //认证请求MQTT连接消息
            var json = SendRequest("10210112", "");
            var result = JsonConvert.DeserializeObject<Unit3AuthenticationResponse>(json);

            if (result.Code != 200)
            {
                return Error(result.Msg);
            }

            if (result.Data != null)
            {

            }

            return null;
        }
        // AES加密方法
        private string AesEncrypt(string plainText, string key)
        {
            using (Aes aesAlg = Aes.Create())
            {
                // 这里假设使用密钥的前16字节作为AES密钥（根据实际情况调整）
                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                Array.Resize(ref keyBytes, 16); // 确保密钥长度为16字节（AES-128）

                aesAlg.Key = keyBytes;
                aesAlg.Mode = CipherMode.ECB; // 根据实际加密模式调整
                aesAlg.Padding = PaddingMode.PKCS7;

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        return Convert.ToBase64String(msEncrypt.ToArray());
                    }
                }
            }
        }

        // 发送请求方法 设备认证
        private string SendRequest(string deviceId, string productKey)
        {
            try
            {
                // 构建请求URL
                string url = $"https://iot.ganlin.com/api/v2/daan";

                // 生成时间戳
                long timestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

                // 构建请求体
                var requestBody = new Unit3AuthenticationRequest
                {
                    device_id = deviceId,
                    product_key = productKey,
                    time = timestamp
                };

                // 生成签名原文
                string signPlainText = $"{deviceId}{productKey}{timestamp}";
                // 进行AES加密得到签名
                string sign = AesEncrypt(signPlainText, aesKey);

                // 序列化请求体为JSON
                string jsonBody = JsonConvert.SerializeObject(requestBody);

                // 创建HTTP请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                // 添加头部信息
                request.Headers.Add("sign", sign);

                // 写入请求体
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonBody);
                }

                // 获取响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                return $"请求失败: {ex.Message}";
            }
        }

    }
    public class Unit3AuthenticationRequest
    {
        public string device_id { get; set; }
        public string product_key { get; set; }
        public long time { get; set; }
    }
    /// <summary>
    /// 接口响应根对象
    /// </summary>
    public class Unit3AuthenticationResponse
    {
        /// <summary>
        /// 状态码（200表示成功）
        /// </summary>
        [JsonProperty("code")]
        public int Code { get; set; }

        /// <summary>
        /// 状态描述
        /// </summary>
        [JsonProperty("msg")]
        public string Msg { get; set; }

        /// <summary>
        /// 业务数据
        /// </summary>
        [JsonProperty("data")]
        public Unit3AuthenticationResponseData Data { get; set; }
    }

    /// <summary>
    /// 响应中的业务数据
    /// </summary>
    public class Unit3AuthenticationResponseData
    {
        /// <summary>
        /// 设备录入凭证
        /// </summary>
        [JsonProperty("token")]
        public string Token { get; set; }

        /// <summary>
        /// 6位字符，用于拼接clientid
        /// </summary>
        [JsonProperty("client_key")]
        public string ClientKey { get; set; }

        /// <summary>
        /// MQTT连接账号
        /// </summary>
        [JsonProperty("username")]
        public string Username { get; set; }

        /// <summary>
        /// MQTT连接密码
        /// </summary>
        [JsonProperty("password")]
        public string Password { get; set; }

        /// <summary>
        /// MQTT连接协议头（如tcp://）
        /// </summary>
        [JsonProperty("host")]
        public string Host { get; set; }

        /// <summary>
        /// MQTT端口（字符串类型）
        /// </summary>
        [JsonProperty("port")]
        public string Port { get; set; }

        /// <summary>
        /// MQTT服务IP或域名
        /// </summary>
        [JsonProperty("ip")]
        public string Ip { get; set; }

        /// <summary>
        /// 云平台clientId
        /// </summary>
        [JsonProperty("server_client_id")]
        public string ServerClientId { get; set; }

        /// <summary>
        /// 设备订阅主题前缀（接收命令）
        /// </summary>
        [JsonProperty("order_topic")]
        public string OrderTopic { get; set; }

        /// <summary>
        /// 云平台订阅主题前缀（接收设备信息）
        /// </summary>
        [JsonProperty("info_topic")]
        public string InfoTopic { get; set; }

        /// <summary>
        /// 设备上传信息结果返回主题
        /// </summary>
        [JsonProperty("result_device_topic")]
        public string ResultDeviceTopic { get; set; }

        /// <summary>
        /// 云平台下发信息结果返回主题
        /// </summary>
        [JsonProperty("result_server_topic")]
        public string ResultServerTopic { get; set; }
    }
}
